import React from 'react';
import ReactDOM from 'react-dom';
import ReactJson from 'react-json-view';
import AppBar from 'material-ui/AppBar';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Truedata from './Truedata.js';
import DataUtil from './DataUtil.js';
import Dialog from 'material-ui/Dialog';
import CircularProgress from 'material-ui/CircularProgress';
import Snackbar from 'material-ui/Snackbar';
import Avatar from 'material-ui/Avatar';
import "./css/AnalyzeProcedure.less";

class AnalyzeProcedure extends React.Component {
    constructor(props) {
        super();
        this.state = {
            raReady: props.raReady,
            procedure:'',
            hasProceduce: true,
            snackbarOpen: false,
            snackbarMsg: '',
            autoHideDuration: 4000,
            loadingOpen: false,
            analyzeResult: null,
            resultOpen: false
        }
        // 监听分析存储过程
        this.handleAnalyzeProcedure = this.handleAnalyzeProcedure.bind(this);
        // 文本输入
        this.fillText = this.fillText.bind(this);
        // 打开结果框
        this.handleOpenResultDialog = this.handleOpenResultDialog.bind(this);
        // 关闭
        this.handleCloseResultDialog = this.handleCloseResultDialog.bind(this);
	}
    // 打开结果框
    handleOpenResultDialog(){
        this.setState({resultOpen: true});
    }
    // 文本输入
    fillText(event, index, value){
        let _value = event.target.value;
        if(!_value || !_value.trim() || !_value.trim().length){
            this.setState({hasProceduce: false});
        }else{
            this.setState({hasProceduce: true});
        }
        this.setState({
            'procedure':_value
        });
    }
    // 关闭snackbar
    closeSnackbar(){
        setTimeout(()=>{
            this.setState({snackbarOpen:false});
        },4000);
    }
    // 监听提交
    handleAnalyzeProcedure(){
        let procedure = this.state.procedure;
        if(!procedure || !procedure.trim() || !procedure.trim().length){
            this.setState({hasProceduce:false});
            return;
        }
        this.state.raReady.queryOption['params'] = {"sql":procedure};
        // 显示loading
        this.setState({
            loadingOpen: true
        });
        // 开始分析
        this.state.raReady.clearGraph();
        Truedata.query(
        	this.state.raReady.queryOption,
        	(err,result)=>{
                this.setState({ loadingOpen: false });
                if(err){
                    this.setState({snackbarMsg: err.message,snackbarOpen: true});
                    this.closeSnackbar();
                    return;
                }
                if(!result){
                    this.setState({snackbarMsg: '分析完成，请检查存储过程！',snackbarOpen: true});
                    this.closeSnackbar();
                    return;
                }
                this.setState({result: result});
                console.log('result-----------',result);
                let queryResult = DataUtil.cloneObject(result);
                let graphData = DataUtil.transformData(queryResult);
                console.log('graphData-----------',graphData);
                this.state.raReady.update(graphData);
        });
    }
    // 监听关闭result dialog
    handleCloseResultDialog(){
        this.setState({resultOpen: false});
    }
    generateLoadingDialog(){
        let loadingHtml = [],
            loadingKey = 'loading-dialog';
        loadingHtml.push(<Dialog key={loadingKey}
                                    modal={false}
                                    open={this.state.loadingOpen}
                                    contentStyle={{textAlign:'center'}}
                                    paperClassName="loading-content"
                                    style={{marginTop:'-100px'}}
                                    children={<CircularProgress size={80} thickness={7}/>}>
                        </Dialog>);
        return loadingHtml;
    }
    // 生成结果弹出
    generateResultDialog(){
        let resultHtml = [],
            resultDialogKey = 'result-dialog';
        resultHtml.push(<Dialog key={resultDialogKey}
                                title="存储过程分析结果"
                                onRequestClose={this.handleCloseResultDialog.bind(this)}
                                autoScrollBodyContent={true}
                                modal={false}
                                open={this.state.resultOpen}>
                            <ReactJson src={this.state.result}
                                    name="返回数据"
                                    iconStyle="circle"
                                    style={{marginTop:20}}/>
                        </Dialog>);
        return resultHtml;
    }
	render() {
        let contentHtml = [];
        // title
        let titleKey = 'analyze-procedure-title';
        contentHtml.push(<AppBar
                            iconElementLeft={<Avatar
                                                src="./image/Analysis.png"
                                                size={42}/>}
                            key={titleKey}
                            title="存储过程分析"
                            titleStyle={{fontSize: '18px'}}
                            style={{backgroundColor: '#212121'}}/>);
        // procedure from
        let formKey = 'procedure-form',
            formHtml = [];
        formHtml.push(<TextField
                        key="proceduce"
                        floatingLabelText="存储过程"
                        floatingLabelFixed={true}
                        errorText={this.state.hasProceduce?'':'必填'}
                        multiLine={true}
                        rows={8}
                        rowsMax={8}
                        fullWidth={true}
                        floatingLabelStyle={{fontSize: '20px'}}
                        value={this.state.procedure?this.state.procedure:''}
                        onChange={this.fillText.bind(this)}/>);
        formHtml.push(<RaisedButton
                        key="form-btn"
                        label="开始分析"
                        primary={true}
                        onClick={this.handleAnalyzeProcedure.bind(this)}/>)
        contentHtml.push(<div key={formKey} style={{width:'80%',margin:'0 auto'}}>
                            {formHtml}
                          </div>);
        // 加载进度
        let loadingHtml = this.generateLoadingDialog();
        // 消息提示
        let messageHtml = [];
        // 添加消息提示框
        messageHtml.push(<Snackbar
                          key="editor-snackbar"
                          open={this.state.snackbarOpen}
                          message={this.state.snackbarMsg}
                          autoHideDuration={this.state.autoHideDuration}/>);
        // 查看结果
        let resultHtml = [];
        if(this.state.result){
            resultHtml.push(<div
                                key="result-data"
                                className="result-data"
                                title="查看数据"
                                onClick={this.handleOpenResultDialog.bind(this)}>
                                <img src="./image/view-data.png"/>
                            </div>);
        }
        // 结果弹出
        let resultDialogHtml = this.generateResultDialog();
		return (<div>
                    {contentHtml}
                    {resultHtml}
                    {loadingHtml}
                    {messageHtml}
                    {resultDialogHtml}
                </div>);
	}
}
export default AnalyzeProcedure;
